package cn.bellychang.leetcode.question144;

import java.util.ArrayList;
import java.util.List;

/**
 * Given the root of a binary tree, return the preorder traversal of its nodes' values.
 * <p>
 * Follow up: Recursive solution is trivial, could you do it iteratively?
 *
 * @author ChangLiang
 * @date 2021/2/7
 */
public class Solution {

    List<Integer> list = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {
        traverseTree(root);
        return list;
    }

    private void traverseTree(TreeNode node) {
        if (node == null) {
            return;
        }
        if (node.left == null && node.right == null) {
            list.add(node.val);
            return;
        }
        list.add(node.val);
        traverseTree(node.left);
        traverseTree(node.right);
    }
}
